package com.calvin.study.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.calvin.study.feign.OrderFeignClient;
import com.calvin.study.service.OrderService;

import cloud.alibaba.study.entity.base.RespCodeEnum;
import cloud.alibaba.study.entity.base.ResponseVo;

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private DiscoveryClient discoveryClient;
	@Value("${server.port}")
	private String serverPort;
	@Value("${spring.application.name}")
	private String springApplicationName;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private OrderFeignClient orderFeignClient;

	/**
	 * @Title: getNacos @Description: 验证我们当前应用是否注册到Nacos服务 @date: 2021年12月17日
	 * 上午10:50:16 @version: @return @throws
	 */
	@GetMapping("getNacos")
	private @ResponseBody ResponseVo getNacos() {
		System.out.println(springApplicationName + ":" + serverPort);
		List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("service-user");
		return ResponseVo.success(serviceInstanceList);
	}

	@GetMapping("getOrderList")
	public @ResponseBody ResponseVo getOrderList() {
		try {
			ResponseVo resp = restTemplate.getForObject("http://service-order/order/getOrderList", ResponseVo.class);
			ResponseVo feignResp = orderFeignClient.getOrderList();
			return resp;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseVo.failure(RespCodeEnum.FAIL, e.getMessage());
		}
	}

	@GetMapping("placeOrder")
	public @ResponseBody ResponseVo placeOrder() {
		try {
			ResponseVo resp = orderFeignClient.placeOrder();
			return resp;
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseVo.failure(RespCodeEnum.FAIL, e.getMessage());
		}
	}
}
